package com.shanling.shanlingcontroller.ui.activity;

        import android.Manifest;
        import android.animation.ObjectAnimator;
        import android.os.Bundle;
        import android.util.Log;
        import android.view.View;
        import android.view.animation.Animation;
        import android.widget.Button;
        import android.widget.ImageView;
        import android.widget.LinearLayout;
        import android.widget.ProgressBar;
        import android.widget.RelativeLayout;
        import android.widget.TextView;

        import com.qualcomm.qti.libraries.gaia.GAIA;
        import com.qualcomm.qti.libraries.vmupgrade.UpgradeError;
        import com.qualcomm.qti.libraries.vmupgrade.UpgradeManager;
        import com.shanling.shanlingcontroller.CustomApplication;
        import com.shanling.shanlingcontroller.R;
        import com.shanling.shanlingcontroller.base.BaseMVPActivity;
        import com.shanling.shanlingcontroller.bean.BluetoothState;
        import com.shanling.shanlingcontroller.bean.Constants;
        import com.shanling.shanlingcontroller.bean.EventCenter;
        import com.shanling.shanlingcontroller.bean.MybluetoothDevice;
        import com.shanling.shanlingcontroller.http.HttpConstants;
        import com.shanling.shanlingcontroller.persenter.OTAPersenter;
        import com.shanling.shanlingcontroller.persenter.contract.OTAContract;
        import com.shanling.shanlingcontroller.services.csr.MainGaiaManager;
        import com.shanling.shanlingcontroller.services.csr.UpgradeGaiaManager;
        import com.shanling.shanlingcontroller.utils.PermissionsUtils;
        import com.shanling.shanlingcontroller.utils.ThreadPoolProxyFactory;
        import com.shanling.shanlingcontroller.utils.ToastUtils;

        import org.greenrobot.eventbus.EventBus;
        import org.litepal.LitePal;

        import java.io.File;
        import java.text.DecimalFormat;
        import java.util.List;

        import butterknife.BindView;
        import butterknife.ButterKnife;
        import butterknife.OnClick;

public class OTAActivity extends BaseMVPActivity<OTAContract.Presenter> implements OTAContract.View, PermissionsUtils.onGetpermissons, UpgradeGaiaManager.GaiaManagerListener {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.rl_head)
    RelativeLayout rlHead;
    @BindView(R.id.iv_check)
    ImageView ivCheck;
    @BindView(R.id.tv_check)
    TextView tvCheck;
    @BindView(R.id.bt_ota)
    Button btOta;
    ObjectAnimator objectAnimator;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.ll_version)
    LinearLayout llVersion;
    int state = 0;//0 检测升级 1 下载 2 升级中   3  升级成功
    String downloadUrl;
    @BindView(R.id.tv_progress)
    TextView tvProgress;
    @BindView(R.id.pb)
    ProgressBar pb;
    private int bleType;
    private UpgradeGaiaManager mUpgradeGaiaManager;
    private boolean isOnCheck;

    @Override
    protected void getBundleExtras(Bundle extras) {

    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_ota;
    }

    @Override
    protected void initViewsAndEvents() {
        starAnimator();
        PermissionsUtils.setPermissons(this);
    }

    private void starAnimator() {
        objectAnimator = ObjectAnimator.ofFloat(ivCheck, "rotation", 0f, 360f);
        objectAnimator.setDuration(800);
        objectAnimator.setRepeatCount(Animation.INFINITE);
        objectAnimator.start();
    }

    @Override
    protected void initData() {
        List<MybluetoothDevice> mybluetoothDevices = LitePal.where("mac = ?", preferenceUtil.getBleMac()).find(MybluetoothDevice.class);
        MybluetoothDevice mybluetoothDevice = mybluetoothDevices.get(0);
        bleType = mybluetoothDevices.get(0).getType();
        Log.e("weiyu", "类型" + mybluetoothDevice.getType() + "版本" + mybluetoothDevice.getCurrent_Version());
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mPersenter.getLatestversion(bleType, mybluetoothDevice.getCurrent_Version());
            }
        }, 900);
    }

    @Override
    protected boolean isBindEventBusHere() {
        return true;
    }

    @Override
    protected void onEventComing(EventCenter eventCenter) {
        switch (eventCenter.getEventCode()) {
            case Constants.UPGRADE_REQUEST_CONFIRMATION:
                int confirmation = (int) eventCenter.getData();
                askForConfirmation(confirmation);
                break;
            case Constants.GAIA_PACKET:
                byte[] data = (byte[]) eventCenter.getData();
                mUpgradeGaiaManager.onReceiveGAIAPacket(data);
                break;
            case Constants.BLUETOOTH_STATE:
                BluetoothState state = (BluetoothState) eventCenter.getData();
                if (state == null) {
                    return;
                }
                switch (state.getState()) {
                    case Constants.CONNECTED:
                        onUpgradeFinish();
                        break;
                    case Constants.DISCONNECTED:
                        Runnable runnable = new Runnable() {
                            @Override
                            public void run() {
                                EventBus.getDefault().post(new EventCenter<>(Constants.BCAK_TO_BLUETOOTH, true));
                                Log.e("weiyu", "连接" + customApplication.isConnected());
                                if (customApplication.isConnected()) {
                                    return;
                                }
                                mHandler.postDelayed(this, 8000);
                            }
                        };
                        mHandler.post(runnable);
                        break;
                }
                break;
        }
    }

    private void askForConfirmation(int confirmation) {
        switch (confirmation) {
            case UpgradeManager.ConfirmationType.COMMIT:
                break;
            case UpgradeManager.ConfirmationType.IN_PROGRESS:
                // no obligation to ask for confirmation as the commit confirmation should happen next
                break;
            case UpgradeManager.ConfirmationType.TRANSFER_COMPLETE:
                tvCheck.setText(R.string.Installation_complete);
                pb.setVisibility(View.VISIBLE);
                break;
            case UpgradeManager.ConfirmationType.BATTERY_LOW_ON_DEVICE:
                break;
            case UpgradeManager.ConfirmationType.WARNING_FILE_IS_DIFFERENT:
                break;
        }
        if (mUpgradeGaiaManager != null) {
            mUpgradeGaiaManager.sendConfirmation(confirmation, true);
        }
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        return false;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        return null;
    }

    @Override
    public void getLatestversionFaild() {
        state = 0;
        isOnCheck=false;
        objectAnimator.end();
        tvCheck.setText(getString(R.string.Version_checkfailed));
        btOta.setVisibility(View.VISIBLE);
        btOta.setText(R.string.try_again);
    }

    @Override
    public void getLatestversionSuccess(String versionCode, String url) {
        state = 1;
        objectAnimator.end();
        isOnCheck=false;
        downloadUrl = HttpConstants.OTA_URL + url;
        btOta.setVisibility(View.VISIBLE);
        tvCheck.setText(getString(R.string.upgrade_now));
        btOta.setText(getString(R.string.Start_upgrading));
        llVersion.setVisibility(View.VISIBLE);
        tvVersion.setText("v" + versionCode);
    }

    @Override
    public void Islatestversion() {
        state = 0;
        objectAnimator.end();
        isOnCheck=false;
        btOta.setVisibility(View.VISIBLE);
        tvCheck.setText(getString(R.string.Currently_latestversion));
        btOta.setText(R.string.try_again);
    }

    @Override
    public void onDownloadFaild() {
        state = 1;
        isOnCheck=false;
        ivCheck.setImageResource(R.drawable.ota_img_fail);
        tvCheck.setText(R.string.Upgrade_failed);
        btOta.setVisibility(View.VISIBLE);
        btOta.setText(R.string.try_again);
        tvProgress.setVisibility(View.GONE);
    }

    @Override
    public void onDownloadSuccess() {
        isOnCheck=false;
        switch (bleType) {
            case 1:
                mPersenter.StartUS1IOTA(this,Constants.LOCAL_FIRMWARE_PATH + Constants.FILE_NAME);
                break;
            case 2:
                mPersenter.startUS1OTA(this,Constants.LOCAL_FIRMWARE_PATH + Constants.FILE_NAME);
                break;
            case 3:
                mUpgradeGaiaManager = new UpgradeGaiaManager(this, GAIA.Transport.BR_EDR);
                File file = new File(Constants.LOCAL_FIRMWARE_PATH + Constants.FILE_NAME);
                mPersenter.startCSROTA(mUpgradeGaiaManager, file);
                break;
        }
    }

    @Override
    public void onDawnload(String progress) {
        tvCheck.setText(R.string.Upgrade_hint);
        tvProgress.setText(progress);

    }

    @Override
    public void onOTAFaild() {
      onUpgradeError(null);
    }
    @Override
    public void onOTASuccess() {
        tvCheck.setText(R.string.Installation_complete);
        pb.setVisibility(View.VISIBLE);
    }
    @Override
    public void onProgress(float progress) {
          progress = progress / 2 + 50;
        tvProgress.setText(progress+"%");
        if (progress ==100) {
            tvCheck.setText(getString(R.string.installing));
        }
    }
    @Override
    protected OTAContract.Presenter createPresenter() {
        return new OTAPersenter(this);
    }

    @OnClick({R.id.iv_back, R.id.bt_ota})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                 onBackPressed();
                finish();
                break;
            case R.id.bt_ota:
                getPermisson();
                break;
        }
    }


    private void getPermisson() {
        PermissionsUtils.getPermisson(this,Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE );
    }

    private void doDownload() {
        File file = new File(Constants.LOCAL_FIRMWARE_PATH + Constants.FILE_NAME);
        if (file.exists()) {
            file.delete();
        }
        llVersion.setVisibility(View.GONE);
        state = 2;
        ivCheck.setImageResource(R.drawable.ota_img_process);
        mPersenter.download(downloadUrl, Constants.FILE_NAME);
        tvProgress.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        objectAnimator.end();
        if (runnable != null) {
            ThreadPoolProxyFactory.getNormalThreadPoolProxy().remove(runnable);
        }
        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    public void onBackPressed() {
        if (state != 2) {
            super.onBackPressed();
        } else {
            ToastUtils.showToast(this, R.string.Firmware_upgrade_inprogress);
        }
    }

    @Override
    public void onGetPermissonSuccess() {
        btOta.setVisibility(View.GONE);
        if(isOnCheck){
            return;
        }
        isOnCheck=true;
        switch (state) {
            case 0:
                objectAnimator.start();
                initData();
                break;
            case 1:
                doDownload();
                break;
        }
    }

    @Override
    public void onGetPermissonFailed() {
        ToastUtils.showToast(this, R.string.open_permission);
    }

    public void onResumePointChanged(int point) {
    }

    @Override
    public void onUpgradeError(UpgradeError error) {
        state = 1;
        ivCheck.setImageResource(R.drawable.ota_img_fail);
        tvCheck.setText(R.string.Upgrade_failed);
        btOta.setVisibility(View.VISIBLE);
        btOta.setText(R.string.try_again);
        tvProgress.setVisibility(View.GONE);
    }

    @Override
    public void onUploadProgress(double percentage) {
        double progress = percentage / 2 + 50;
        DecimalFormat df = new DecimalFormat("#.00");
        tvProgress.setText(df.format(progress) + "%");
        if (progress > 99) {
            tvProgress.setText("100%");
            tvCheck.setText(getString(R.string.installing));
        }
    }

    private boolean isSend;
    private Runnable runnable;

    @Override
    public boolean sendGAIAUpgradePacket(byte[] packet, boolean isTransferringData) {
        runnable = new Runnable() {
            @Override
            public void run() {
                isSend = CustomApplication.getInstance().getmGAIABREDRProvider().sendGAIAUpgradePacket(packet, true);
                Log.e("weiyu", "state发送" + isSend);
            }
        };
        ThreadPoolProxyFactory.getNormalThreadPoolProxy().execute(runnable);
        return true;
    }

    @Override
    public void onUpgradeFinish() {
        state = 3;
        pb.setVisibility(View.GONE);
        ivCheck.setImageResource(R.drawable.ota_img_success);
        tvCheck.setText(R.string.Update_successed);
        btOta.setVisibility(View.GONE);
        tvProgress.setVisibility(View.GONE);

    }

    @Override
    public void onVMUpgradeDisconnected() {
        if (!mUpgradeGaiaManager.isUpgrading()) {
            mUpgradeGaiaManager.reset();
        }
    }

}
